package com.example.drools.service;

import com.example.drools.dto.RecommendRequest;
import com.example.drools.model.Context;
import com.example.drools.model.Recommendation;
import com.example.drools.model.Score;
import com.example.drools.model.UserProfile;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class RecommendationService {

    private final KieContainer kieContainer;

    public RecommendationService(KieContainer kieContainer) {
        this.kieContainer = kieContainer;
    }

    public List<Recommendation> recommend(RecommendRequest req) {
        KieSession kieSession = kieContainer.newKieSession();
        try {
            // 可选：将 agenda-group "recommendation" 设为焦点
            kieSession.getAgenda().getAgendaGroup("recommendation").setFocus();

            UserProfile user = new UserProfile();
            user.setId(req.getUserId());
            user.setSegments(req.getSegments());
            user.setRegion(req.getRegion());
            
            Context ctx = new Context();
            ctx.setChannel(req.getChannel());
            ctx.setPage(req.getPage());
            Score score = new Score(req.getUserId(), "engagement", req.getEngagementScore() == null ? 0 : req.getEngagementScore());

            kieSession.insert(user);
            kieSession.insert(ctx);
            kieSession.insert(score);

            kieSession.fireAllRules();

            Collection<?> facts = kieSession.getObjects(obj -> obj instanceof Recommendation);
            List<Recommendation> result = new ArrayList<>();
            for (Object f : facts) {
                result.add((Recommendation) f);
            }
            return result;
        } finally {
            kieSession.dispose();
        }
    }
}